import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


class Message {
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Message{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}

@WebServlet("/message1")
public class MessageServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    private List<Message> list = new ArrayList<>();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 读取前段发来的请求，将数据保存到服务器
        Message message = objectMapper.readValue(req.getInputStream(),Message.class);
        System.out.println("请求中的数据: " + message);

        // 将数据保存到集合类中
        list.add(message);

        // 给客户端返回响应
        resp.setStatus(200);
        resp.setContentType("application/json; charSet=utf8");
        resp.getWriter().write("ok");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 给客户端返回响应
        resp.setStatus(200);
        resp.setContentType("application/json; charset=utf8");
        String respJson = objectMapper.writeValueAsString(list);
        resp.getWriter().write(respJson);
    }
}
